import { GlobVar } from "../global";
import { Context } from "koa";
const svgCaptcha = require("svg-captcha");
import Router from "@koa/router";
import proxy from "../middlewares/proxy";
import { handleLogin, handleLogout } from "./../controllers/session";
const convert = require("koa-convert");
import bodyParser from "koa-bodyparser";
import { send_gateway_request, send_origin_request } from "../libs/request";
const router = new Router();
import { getFileVersion, getServerConfig, getManifest } from "../libs/utils";
// import handleSendEmail from '../components/sendemail';

import { EcosProxy } from "../proxy";
import { remove, uniq } from "lodash";

const { client: clientConfig, server: serverConfig } = getServerConfig();

const parseBody = convert(
  bodyParser({
    formLimit: "200kb",
    jsonLimit: "200kb",
    // bufferLimit: '4mb',
  })
);

router
  // ecos api
  .use(proxy("/ecos/(.*)", EcosProxy))
  .post("/login", parseBody, handleLogin)
  .get("/logout", handleLogout)
  .get("/captcha", (ctx: any) => {
    const cap = svgCaptcha.create({
      size: 4, // 验证码长度
      width: 110,
      height: 28,
      fontSize: 28,
      ignoreChars: "0oO1ilI", // 验证码字符中排除 0o1i
      noise: 2, // 干扰线条的数量
      color: false, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
      // background: '#f0f0f0', // 验证码图片背景颜色
    });
    const img = cap.data; // 验证码
    const text = cap.text.toLowerCase(); // 验证码字符，忽略大小写
    ctx.session.captcha = text;
    ctx.type = "svg";
    ctx.body = img;
  })
  .get("/api/user", (ctx: any) => {
    const data = [
      {
        id: 1,
        name: "zhao",
        finish: true,
      },
      {
        id: 2,
        name: "qian1222211",
        finish: true,
      },
    ];
    // ctx.status = 502;
    ctx.body = {
      users: data,
      nextPage: 12,
    };
  })
  // page entry
  .all("(.*)", async (ctx: Context) => {
    const manifest = getManifest("main");
    const userinfo = ctx.session.userinfo || { roles: [] };
    await ctx.render("index", {
      manifest,
      t: ctx.t.bind(ctx),
      isDev: GlobVar.MODE_DEV,
      version: getFileVersion,
      title: clientConfig.title,
      config: JSON.stringify(clientConfig),
      userinfo: JSON.stringify(userinfo) || "{}",
    });
  });

export { router };
